export interface DemoPortfolioPosition {
  symbol: string;
  name: string;
  quantity: number;
  avgPrice: number;
  lastPrice: number;
}

export interface DemoPortfolioResponse {
  cash: number;
  positions: DemoPortfolioPosition[];
  totalValue: number;
  updatedAt: string;
}

export interface DemoMarketItem {
  symbol: string;
  name: string;
  lastPrice: number;
}

export interface DemoMarketResponse {
  items: DemoMarketItem[];
  updatedAt: string;
}

export type DemoOrderSide = "buy" | "sell";

export interface DemoOrderRecord {
  id: string;
  symbol: string;
  name: string;
  side: DemoOrderSide;
  quantity: number;
  price: number;
  executedAt: string;
}

export interface DemoOrdersResponse {
  items: DemoOrderRecord[];
  updatedAt: string;
}

export interface DemoOrderResponse {
  message: string;
  portfolio: {
    cash: number;
    positions: DemoPortfolioPosition[];
  };
}

const DEFAULT_BACKEND_URL = "http://localhost:4000";

const backendBaseUrl =
  (import.meta as any).env?.VITE_BACKEND_URL ?? DEFAULT_BACKEND_URL;

export async function fetchDemoPortfolio(): Promise<DemoPortfolioResponse> {
  const res = await fetch(`${backendBaseUrl}/api/demo/portfolio`);
  if (!res.ok) {
    throw new Error(`获取 demo 资产失败：${res.status}`);
  }
  return res.json();
}

export async function fetchDemoMarket(): Promise<DemoMarketResponse> {
  const res = await fetch(`${backendBaseUrl}/api/demo/market`);
  if (!res.ok) {
    throw new Error(`获取 demo 行情失败：${res.status}`);
  }
  return res.json();
}

export async function fetchDemoOrders(): Promise<DemoOrdersResponse> {
  const res = await fetch(`${backendBaseUrl}/api/demo/orders`);
  if (!res.ok) {
    throw new Error(`获取 demo 订单历史失败：${res.status}`);
  }
  return res.json();
}

export async function createDemoOrder(params: {
  symbol: string;
  quantity: number;
  side?: DemoOrderSide;
}): Promise<DemoOrderResponse> {
  const res = await fetch(`${backendBaseUrl}/api/demo/order`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(params)
  });

  const data = await res.json();
  if (!res.ok) {
    throw new Error(data?.error || "下单失败");
  }
  return data;
}


